<template>
  <div class="container">
    <!-- 左侧的漫画框部分 -->
    <div class="comic-section">
      <el-button type="primary" @click="printPreview">打印预览</el-button>
      <el-button type="success" @click="exportToJPG">导出为JPG</el-button>
      <el-button type="success" @click="goToImageCropper">前往裁剪</el-button>

      <div class="comic-container" ref="comicContainer">
        <div v-for="(frame, index) in frames" :key="index" :class="['comic-frame', frame.size]" :style="frame.styles">
          <label v-if="!frame.image" class="upload-label" :for="'upload' + index">
            点击上传图片{{ index + 1 }}
          </label>
          <input
            v-if="!frame.image"
            type="file"
            :id="'upload' + index"
            accept="image/*"
            @change="onImageUpload($event, index)"
          />

          <img
            v-if="frame.image"
            :src="frame.image"
            class="uploaded-image"
            @dblclick="changeImage(index)"
          />
        </div>
      </div>
      
      <!-- 添加框数量选择 -->
     
    </div>

    <!-- 右侧的样式设置表单 -->
    <div class="settings-section">
      <h3>设置每个方框的样式</h3>
      <el-form :model="formModel" label-width="100px">
        <el-form-item label="模板选择">
          <el-select v-model="formModel.selectedTemplate" placeholder="选择框架模板" @change="applyTemplate">
            <el-option
              v-for="(template, index) in templates"
              :key="index"
              :label="template.label"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="边框颜色">
          <el-color-picker v-model="formModel.borderColor" show-alpha></el-color-picker>
        </el-form-item>
        <el-form-item label="边框宽度">
          <el-slider v-model="formModel.borderWidth" min="1" max="10" step="1" label="宽度: {{ formModel.borderWidth }}"></el-slider>
        </el-form-item>
        <el-form-item label="背景颜色">
          <el-color-picker v-model="formModel.backgroundColor" show-alpha></el-color-picker>
        </el-form-item>
        <el-form-item label="选择方框">
          <el-select v-model="formModel.selectedFrame" placeholder="选择方框">
            <el-option
              v-for="(frame, index) in frames"
              :key="index"
              :label="'框 ' + (index + 1)"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="applyStyles">应用样式</el-button>

        <el-form-item label="框数量">
        <el-select v-model="frameCount" placeholder="选择框数量">
          <el-option v-for="num in 6" :key="num" :label="num" :value="num" />
        </el-select>
      </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import html2canvas from "html2canvas";

export default {
  name: "ComicFrame",
  setup() {
    const frameCount = ref(1); // 选择框的数量
    const templates = ref([
      { label: "大矩形", size: "large-rect", height: "80mm", clipPath: "" },
      { label: "高矩形", size: "tall-rect", height: "80mm", clipPath: "" },
      { label: "宽矩形", size: "wide-rect", height: "60mm", clipPath: "" },
      { label: "小矩形", size: "small-rect", height: "50mm", clipPath: "" },
      { label: "梯形框", size: "trapezoid-frame", height: "70mm", clipPath: "polygon(10% 0, 90% 0, 100% 100%, 0% 100%)" },
    ]);

    const frames = ref([]);
    
    // 表单的样式设置
    const formModel = ref({
      borderColor: "#000000",
      borderWidth: 2,
      backgroundColor: "rgba(255, 255, 255, 0.7)",
      selectedFrame: 0,
      selectedTemplate: 0,
    });

    // 创建框架
    const createFrames = () => {
      frames.value = Array.from({ length: frameCount.value }, (_, index) => ({
        size: "large-rect",
        image: null,
        styles: {},
      }));
    };

    // 监听框架数量变化
    watch(frameCount, createFrames, { immediate: true });

    const applyTemplate = () => {
      const selectedTemplate = templates.value[formModel.value.selectedTemplate];
      const selectedFrameIndex = formModel.value.selectedFrame;
      const selectedFrame = frames.value[selectedFrameIndex];

      selectedFrame.size = selectedTemplate.size;
      selectedFrame.styles = {
        ...selectedFrame.styles,
        height: selectedTemplate.height,
        clipPath: selectedTemplate.clipPath,
      };
    };

    const applyStyles = () => {
      const selectedFrameIndex = formModel.value.selectedFrame;
      const selectedFrame = frames.value[selectedFrameIndex];
      selectedFrame.styles = {
        borderColor: formModel.value.borderColor,
        borderWidth: formModel.value.borderWidth + "px",
        backgroundColor: formModel.value.backgroundColor,
      };
    };

    const onImageUpload = (event, index) => {
      const file = event.target.files[0];
      if (file && file.type.startsWith("image/")) {
        const reader = new FileReader();
        reader.onload = () => {
          frames.value[index].image = reader.result;
        };
        reader.readAsDataURL(file);
      } else {
        ElMessage.error("请上传有效的图片文件");
      }
    };

    const router = useRouter();

    const changeImage = (index) => {
      const inputElement = document.createElement("input");
      inputElement.type = "file";
      inputElement.accept = "image/*";
      inputElement.onchange = (event) => onImageUpload(event, index);
      inputElement.click();
    };

    const goToImageCropper = () => {
      router.push({ name: "ImageCropper" });
    };

    const printPreview = () => {
      const comicContainer = document.querySelector(".comic-container");
      const images = comicContainer.querySelectorAll("img");

      let loadedImages = 0;
      const totalImages = images.length;

      if (totalImages === 0) {
        triggerPrint();
        return;
      }

      images.forEach((image) => {
        if (image.complete) {
          loadedImages++;
        } else {
          image.onload = () => {
            loadedImages++;
            if (loadedImages === totalImages) {
              triggerPrint();
            }
          };
        }
      });

      if (loadedImages === totalImages) {
        triggerPrint();
      }

      function triggerPrint() {
        const originalContent = document.body.innerHTML;
        document.body.innerHTML = comicContainer.outerHTML;
        window.print();
        document.body.innerHTML = originalContent;
      }
    };

    const exportToJPG = () => {
  const comicContainer = document.querySelector(".comic-container");
  const tempContainer = document.createElement("div");
  document.body.appendChild(tempContainer);
  
  const clonedComic = comicContainer.cloneNode(true);
  removeStyles(clonedComic);
  
  // 去除背景和阴影
  clonedComic.style.background = 'none';
  clonedComic.style.boxShadow = 'none';
  
  tempContainer.appendChild(clonedComic);

  setTimeout(() => {
    html2canvas(tempContainer, {
      useCORS: true,
    }).then((canvas) => {
      const dataURL = canvas.toDataURL("image/jpeg");
      const link = document.createElement("a");
      link.href = dataURL;
      link.download = "comic_frame.jpg";
      link.click();
      document.body.removeChild(tempContainer);
    });
  }, 100); // 等待100毫秒确保渲染
};


const removeStyles = (element) => {
  element.style.borderRadius = '0'; // 去除容器圆角
  element.style.boxShadow = 'none'; // 去除阴影

  Array.from(element.getElementsByClassName('comic-frame')).forEach(frame => {
    frame.style.borderRadius = '0'; // 去除每个框的圆角
    frame.style.boxShadow = 'none'; // 去除框的阴影
  });

  // 可以添加更多样式去除
  Array.from(element.getElementsByTagName('img')).forEach(img => {
    img.style.borderRadius = '0'; // 去除图片圆角
  });
};


    

    return {
      templates,
      frames,
      formModel,
      frameCount,
      applyTemplate,
      applyStyles,
      onImageUpload,
      changeImage,
      printPreview,
      exportToJPG,
      goToImageCropper,
    };
  },
};
</script>


<style scoped>
/* 主容器 */
.container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  height: 100vh; /* 确保容器高度充满页面 */
}

.comic-section {
  flex: 1;
}

.settings-section {
  width: 30%; /* 设置占页面的 30% */
  height: 100%;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 在打印时移除阴影和圆角 */
@media print {
  .settings-section {
    box-shadow: none; /* 移除阴影 */
    border-radius: 0; /* 移除圆角 */
  }
}

.comic-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: auto;
  gap: 5px;
  width: 210mm;
  height: 297mm;
  padding: 10mm;
  box-sizing: border-box;
  margin: 0 auto;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(230, 230, 230, 0.9));
  border-radius: 15px; /* 圆角效果 */
  border: 5px solid black; /* 添加黑色边框 */
  box-shadow: 0px 12px 24px rgba(0, 0, 0, 0.5);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

/* 打印时移除所有阴影、背景和圆角 */
@media print {
  .comic-container {
    background: none; /* 打印时移除渐变背景 */
    box-shadow: none; /* 打印时移除阴影效果 */
    border-radius: 0; /* 打印时移除圆角效果 */
    border: 5px solid black; /* 保留黑色边框 */
  }
}


/* 各种框的样式 */
.comic-frame {
  position: relative;
  border: 2px solid #000;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px; /* 圆角 */
  background: rgba(255, 255, 255, 0.9); /* 透明背景，增加层次感 */
  box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.5); /* 强化阴影效果 */
  transition: transform 0.3s ease, box-shadow 0.3s ease; /* 添加平滑过渡效果 */
}

/* 打印时移除阴影和圆角 */
@media print {
  .comic-frame {
    box-shadow: none; /* 移除阴影 */
    border-radius: 0; /* 移除圆角 */
  }
}

.large-rect {
  grid-column: span 3;
  height: 80mm;
}

.tall-rect {
  grid-column: span 1;
  height: 80mm;
}

.wide-rect {
  grid-column: span 2;
  height: 60mm;
}

.small-rect {
  grid-column: span 1;
  height: 50mm;
}

.trapezoid-frame {
  grid-column: span 2;
  height: 70mm;
  clip-path: polygon(10% 0, 90% 0, 100% 100%, 0% 100%);
}

/* 上传按钮样式 */
.upload-label {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 18px;
  color: #666;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 10px; /* 圆角效果 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

/* 打印时移除上传按钮的阴影和圆角 */
@media print {
  .upload-label {
    box-shadow: none; /* 移除阴影 */
    border-radius: 0; /* 移除圆角 */
  }
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px; /* 图片圆角 */
  box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.4); /* 内阴影效果，增加深度感 */
}

/* 打印时移除图片的阴影和圆角 */
@media print {
  .uploaded-image {
    box-shadow: none; /* 移除阴影 */
    border-radius: 0; /* 移除圆角 */
  }
}

/* 设置每个方框的背景、阴影和圆角效果 */
.settings-section {
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.8), rgba(240, 240, 240, 0.8)); /* 添加渐变背景 */
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 阴影效果 */
}

/* 打印时移除设置区域的阴影和圆角 */
@media print {
  .settings-section {
    box-shadow: none; /* 移除阴影 */
    border-radius: 0; /* 移除圆角 */
  }
}

.el-form-item {
  margin-bottom: 20px; /* 更好的布局 */
}
</style>


